import 'dart:isolate';
import 'package:easy_isolate/easy_isolate.dart';
import 'package:esc_pos_utils_plus/esc_pos_utils_plus.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:image/image.dart' as image;
import 'package:flutter/services.dart';
import 'package:flutter_gprinter/flutter_gprinter.dart';
import 'package:flutter_gprinter/esc_command.dart';
import 'package:flutter_gprinter/flutter_gprinter_platform_interface.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

final _flutterGprinterPlugin = FlutterGprinter();

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';

  int count = 0;

  @override
  void initState() {
    super.initState();
    initPlatformState();
    _init();
  }

  void _init() async {
    await _flutterGprinterPlugin.init();
    _flutterGprinterPlugin.autoConnect();
  }

  void _startPolling() {
    Timer.periodic(const Duration(milliseconds: 100), (timer) {
      setState(() {
        count++;
      });
    });
    Timer.periodic(const Duration(seconds: 20), (timer) {
      RootIsolateToken token = RootIsolateToken.instance!;
    });
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion = await _flutterGprinterPlugin.getPlatformVersion() ??
          'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  Future<List<int>> _printData() async{
      final profile = await CapabilityProfile.load(name: "XP-N160I");
      final generator = Generator(PaperSize.mm58, profile);
      List<int> bytes = [];
      bytes += generator.setGlobalCodeTable('CP1252');
      bytes += generator.text('世纪大道',
          styles: const PosStyles(align: PosAlign.center, width: PosTextSize.size1, height: PosTextSize.size1),
          containsChinese: true);
      bytes += generator.text('google.com');
      bytes += generator.qrcode('www.baidu.com', size: QRSize.size8);
      final List<int> barData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 4];
      bytes += generator.barcode(Barcode.upcA(barData));
      bytes += generator.row([
        PosColumn(
          text: 'col3',
          width: 4,
          styles: PosStyles(align: PosAlign.left, underline: true),
        ),
        PosColumn(
          text: 'col6',
          width: 4,
          styles: PosStyles(align: PosAlign.center, underline: true),
        ),
        PosColumn(
          text: 'col3',
          width: 4,
          styles: PosStyles(align: PosAlign.right, underline: true),
        ),
      ]);

      final ByteData data = await rootBundle.load('assets/images/gray_logo.png');
      final Uint8List imgBytes = data.buffer.asUint8List();
      final img = image.decodePng(imgBytes);
      bytes += generator.imageRaster(img!);
      bytes += generator.feed(2);
      bytes += generator.cut();
      return bytes;
  }

  @override
  Widget build(BuildContext context) {
    var btn = ElevatedButton(onPressed: () {}, child: const Text("测试"));
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            children: [
              Text('Running on: $_platformVersion\n'),
              btn,
              ElevatedButton(
                onPressed: () {
                  _flutterGprinterPlugin.navUsbDevices();
                },
                child: const Text("USB设备"),
              ),
              ElevatedButton(
                onPressed: () {
                  _flutterGprinterPlugin.navBTDevices();
                },
                child: const Text("蓝牙设备"),
              ),
              ElevatedButton(
                onPressed: () {
                  _flutterGprinterPlugin.navWifiDevices();
                },
                child: const Text("Wifi设备"),
              ),
              ElevatedButton(
                onPressed: () async{
                  List<int> bytes = _printData() as List<int>;
                  _flutterGprinterPlugin.addPrintTask(bytes);
                },
                child: const Text("PRINT"),
              ),
              ElevatedButton(
                onPressed: () {
                  _flutterGprinterPlugin.connect("token", (response) {});
                },
                child: const Text("后台打印"),
              ),
              Text("主线程计数器：$count")
            ],
          ),
        ),
      ),
    );
  }
}
